<template>
  <div>
    <f-table
      ref="tableRef"
      @register="register"
      @rowClick="handleDetail">
      <template #header-left>
        <el-button @click="handleExport">{{ t("export") }}</el-button>
        <el-button
          plain
          type="warning"
          @click="handlePass"
          >批量通过</el-button
        >
        <el-button
          type="danger"
          plain
          @click="handleRefuse"
          >批量拒绝</el-button
        >
        <el-button
          type="info"
          plain
          @click="handleEditGroup"
          >批量修改</el-button
        >
      </template>
      <template #table-tabs>
        <el-tabs
          v-model="active"
          @tab-change="methods.reload()">
          <el-tab-pane
            label="全部"
            :name="0"></el-tab-pane>
          <el-tab-pane
            label="从未看课"
            :name="1"></el-tab-pane>
          <el-tab-pane
            label="今日新增"
            :name="2"></el-tab-pane>
          <el-tab-pane
            label="今日未看"
            :name="3"></el-tab-pane>
          <el-tab-pane
            label="今日完播"
            :name="4"></el-tab-pane>
        </el-tabs>
      </template>

      <template #username="{ row }">
        <div
          class="user flex items-center">
          <el-avatar :src="row.avatar"></el-avatar>
          <div class="flex-1 ml-[10px]">
            <div class="flex items-center">
              <div class="mr-[5px] nickname">{{ row.nickname || "--" }}</div>
              <div
                v-if="row.external_userid"
                class="mr-[5px] text-[green] text-[12px]">
                @微信
              </div>
              <el-icon @click.stop="copyEvent(row.nickname)"
                ><CopyDocument
              /></el-icon>
            </div>
          </div>
        </div>
      </template>
      <template #ID="{ row }">
        <div
          class="dblclick">
          {{ row.id || "--" }}
        </div>
      </template>
      <template #store_name="{ row }">
        <div
          class="dblclick">
          {{ row.store_name || "--" }}
        </div>
      </template>
      <template #from_user="{ row }">
        <div
          v-if="row.from_user_name"
          class="flex items-center dblclick">
          <el-avatar :src="row.from_user_avatar"></el-avatar>
          <span>{{ row.from_user_name || "--" }}</span>
        </div>
        <span
          class="dblclick"
          v-else
          >无</span
        >
      </template>
      <template #last_join_time="{ row }">
        <div
          class="dblclick">
          {{ row.last_join_time ? format(row.last_join_time) : "--" }}
        </div>
      </template>
      <template #statistics="{ row }">
        <div
          class="dblclick">
          <p>
            累计答题次数：<span class="text-[red]">{{
              row.dati_count || 0
            }}</span
            >次
          </p>
          <p>
            累计红包发放数：<span class="text-[red]">{{
              row.count_money_num || 0
            }}</span
            >次
          </p>
          <p>
            累计金额：<span class="text-[red]">{{ row.count_money || 0 }}</span
            >元
          </p>
        </div>
      </template>
      <template #jifen="{ row }">
        <div
          class="dblclick">
          {{ row.jifen || 0 }}
        </div>
      </template>
      <template #mobile="{ row }">
        <div
          class="dblclick">
          {{ row.mobile || "--" }}
        </div>
      </template>
      <template #ip="{ row }">
        <div
          class="dblclick">
          {{ row.ip || "--" }}
        </div>
      </template>
      <template #reg_time="{ row }">
        <div
          class="dblclick">
          {{ row.reg_time ? formatRegTime(row.reg_time) : "--" }}
        </div>
      </template>
      <template #status="{ row }">
        <el-dropdown @command="handleEditStatus($event, row)">
          <div
            class="dblclick">
            <el-tag
              v-if="row.status === 1"
              type="success"
              >正常</el-tag
            >
            <el-tag
              v-else-if="row.status === 2"
              type="primary"
              >待审核</el-tag
            >
            <el-tag
              v-else-if="row.status === 3"
              type="danger"
              >已拒绝</el-tag
            >
            <el-tag
              v-else
              type="danger"
              >已拉黑</el-tag
            >
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="1">已通过</el-dropdown-item>
              <el-dropdown-item :command="2">审核中</el-dropdown-item>
              <el-dropdown-item :command="3">已拒绝</el-dropdown-item>
              <el-dropdown-item :command="-1">黑名单</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
      <template #action="{ row }">
        <el-space wrap>
          <el-button
            type="primary"
            text
            @click="handleEdit(row)"
            >{{ t("edit") }}</el-button
          >
          <!-- <el-button type="primary" text @click="handleDetail(row)">{{ t('view') }}</el-button> -->
        </el-space>
      </template>
    </f-table>
    <f-form-model
      ref="formModelRef"
      :is="formModelName"
      @change="() => methods.reload()"></f-form-model>
    <f-detail-drawer
      ref="detailDrawerRef"
      is="UserDetail"></f-detail-drawer>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import { t } from "@/lang";
import FTable, {
  BasicColumn,
  useTable,
} from "@/addon/htscrm/components/f-table";
import {
  tableColumns,
  tableSearchFormItems,
} from "@/addon/htscrm/data/user.list";
import {
  exportDataApi,
  getStoreAllApi,
  getUserListApi,
  updateUserApi,
  postBatchPass,
  postBatchRefuse,
} from "@/addon/htscrm/api";
import FFormModel from "@/addon/htscrm/components/f-form-model";
import FDetailDrawer from "@/addon/htscrm/components/f-detail-drawer";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { CopyDocument } from "@element-plus/icons-vue";
import { useClipboard } from "@vueuse/core";
import { cloneDeep } from "lodash-es";

const active = ref(0);
const router = useRouter();
const formModelRef = ref();
const formModelName = ref("UserForm");

const detailDrawerRef = ref();
const tableRef = ref();
const { methods, register } = useTable({
  rowKey: "id",
  searchFromItems: tableSearchFormItems(t),
  columns: tableColumns(t) as BasicColumn<IUserItem>[],
  beforeFetch: (opt) => {
    const params = cloneDeep(opt);
    if (params.look_day.length) {
      params.look_start_day = params.look_day[0];
      params.look_end_day = params.look_day[1];
      delete params.look_day;
    }
    if (params.canyu.length) {
      params.canyu_min = params.canyu[0];
      params.canyu_max = params.canyu[1];
      delete params.canyu;
    }
    if (params.hongbao_num.length) {
      params.hongbao_min_num = params.hongbao_num[0];
      params.hongbao_max_num = params.hongbao_num[1];
      delete params.hongbao_num;
    }
    if (params.money.length) {
      params.money_min = params.money[0];
      params.money_max = params.money[1];
      delete params.money;
    }
    if (params.jifen.length) {
      params.jifen_min = params.jifen[0];
      params.jifen_max = params.jifen[1];
      delete params.jifen;
    }
    if (params.yaoqing.length) {
      params.yaoqing_min = params.yaoqing[0];
      params.yaoqing_max = params.yaoqing[1];
      delete params.yaoqing;
    }
    params.current_tab = active.value;
    return params;
  },
  api: async (opt) => (await getUserListApi(opt)).data,
});

function format(value: number) {
  if (!value) return "--";
  if (new Date().setHours(0, 0, 0) < value) {
    return "今日";
  }
  const data = parseInt(Date.now() / 1000 + "") - value;
  // 时分秒
  const days = Math.floor(data / (3600 * 24));
  if (days == 1) {
    return "昨日";
  } else {
    return days + "天前";
  }
}

function formatRegTime(timestamp: number) {
  const date = new Date(timestamp * 1000);
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
    date.getDate()
  )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
    date.getSeconds()
  )}`;
}

async function getStoreAll() {
  const res = await getStoreAllApi();
  const formItems = tableSearchFormItems(t);
  formItems[2].childrenComponent.children = res.data.map((item) => {
    return {
      label: item.title,
      value: item.id,
    };
  });

  methods.setFormItems(formItems);
}

/**
 * @description 导出
 */
async function handleExport() {
  let params = methods.getSearchInfo()
  const res = await exportDataApi("users", params);
  if (res.data) {
    const action = await ElMessageBox.confirm(
      "文件导出已添加到下载中心，是否立即前往下载中心",
      t("alert.title"),
      {
        cancelButtonText: "我再看看",
        confirmButtonText: "立即前往",
      }
    );
    console.log(action);

    if (action === "confirm") {
      router.push("/htscrm/system/download");
    }
  }
}

function handleEdit(row: IUserItem) {
  formModelName.value = "UserForm";
  formModelRef.value?.show("编辑用户", row);
}
function handleDetail(row: IUserItem) {
  detailDrawerRef.value?.show("客户详情", row);
}

async function handleEditStatus(value: number, row: IUserItem) {
  const res = await updateUserApi({
    id: row.id,
    status: value,
  });

  if (res.code === 1) {
    ElMessage({
      message: "保存成功",
      type: "success",
    });
    row.status = value;
  }
}

// 复制
const { copy, isSupported, copied } = useClipboard();
const copyEvent = (text: string) => {
  if (!isSupported.value) {
    // ElMessage({
    //     message: t('notSupportCopy'),
    //     type: 'warning'
    // })
  }
  copy(text);
};

/**
 * @description 批量通过
 */
async function handlePass() {
  const rows = tableRef.value?.tableAction.getSelectionRows();

  if (!rows || rows.length === 0) {
    ElMessage({
      message: "请先选择要操作的用户",
      type: "warning",
    });
    return;
  }
  const ids = rows.map((row: any) => row.id).join(",");
  const res = await postBatchPass({ id: ids });
  if (res.code === 1) {
    ElMessage({
      message: "批量通过成功",
      type: "success",
    });
    methods.reload();
  }
}

/**
 * @description 批量修改
 */
async function handleEditGroup() {
  const rows = tableRef.value?.tableAction.getSelectionRows();
  if (!rows || rows.length === 0) {
    ElMessage({
      message: "请先选择要操作的用户",
      type: "warning",
    });
    return;
  }

  const params = {
    id: rows.map((item) => item.id),
    title: rows.map((item) => item.nickname),
    type: '用户',
  }
  formModelName.value = "MultipleEditUserForm";
  formModelRef.value?.show(t("batchGroup"), params);
}

/**
 * @description 批量拒绝
 */
async function handleRefuse() {
  const rows = tableRef.value?.tableAction.getSelectionRows();
  if (!rows || rows.length === 0) {
    ElMessage({
      message: "请先选择要操作的用户",
      type: "warning",
    });
    return;
  }

  try {
    const ids = rows.map((row: any) => row.id).join(",");
    const res = await postBatchRefuse({ id: ids });

    if (res.code === 1) {
      ElMessage({
        message: "批量拒绝成功",
        type: "success",
      });
      methods.reload();
    } else {
      ElMessage({
        message: res.msg || "操作失败",
        type: "error",
      });
    }
  } catch (error) {
    console.error("批量拒绝出错:", error);
    ElMessage({
      message: "操作异常，请稍后重试",
      type: "error",
    });
  }
}

watch(copied, () => {
  if (copied.value) {
    ElMessage({
      message: t("copySuccess"),
      type: "success",
    });
  }
});

onMounted(() => {
  getStoreAll();
});
</script>

<style lang="scss" scoped>
.dblclick {
  cursor: pointer;
}
.user {
  cursor: pointer;
}
.nickname {
  max-width: 85px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
